package com.example.yuejian.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.yuejian.R;
import com.example.yuejian.bean.IsCollection;
import com.example.yuejian.bean.MyEntity;
import com.example.yuejian.common.PictureSelectUtils;
import com.example.yuejian.common.Url;
import com.example.yuejian.view.TitleView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.body.ProgressResponseCallBack;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MyActivity extends BaseActivity {

    private static final String TAG = "MyActivity";
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.name)
    TextView name;
    Handler handler_activity = new mHandler();
    private String uid;
    private Context context;
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            Toast.makeText(MyActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
            PictureSelectUtils.getByAlbum(MyActivity.this);

        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(MyActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(MyActivity.this, 1).show();
            }
        }
    };
    @BindView(R.id.title_activity)
    TitleView title_activity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my);
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        context = this;
        uid = SPUtils.getInstance().getInt("uid") + "";
        title_activity.getRightTextTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startActivity(SearchActivity.class);
            }
        });
    }


    public InputStream Bitmap2InputStream(Bitmap bm, int quality) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
        return new ByteArrayInputStream(baos.toByteArray());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Bitmap bitmap = PictureSelectUtils.onActivityResult(this, requestCode, resultCode, data);
        //String ss[] = PictureSelectUtils.getPath().split("/");
        //Log.d(TAG, "onActivityResult: "+ss[ss.length - 1]);
        try {

            EasyHttp.post("yuejian6/public/index.php/json/my/update_pic")
                    .params("pic", Bitmap2InputStream(bitmap, 100), "tmp.jpg", new ProgressResponseCallBack() {
                        @Override
                        public void onResponseProgress(long bytesWritten, long contentLength, boolean done) {
                            if (done) {
                                ToastUtils.showShort("上传成功");
                            }
                        }
                    }).params("user_id", uid)
                    .execute(new SimpleCallBack<String>() {
                        @Override
                        public void onSuccess(String data) {
                            Log.d(TAG, "onSuccess: " + data);
                            Message msg = Message.obtain(); // 实例化消息对象
                            msg.what = 0; // 消息标识
                            msg.obj = data; // 消息内容存放

                            handler_activity.sendMessage(msg);
                        }

                        @Override
                        public void onError(ApiException error) {
                            Log.d(TAG, "onFailed: " + error);
                        }
                    });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.img)
    void setimg() {

        if (AndPermission.hasAlwaysDeniedPermission(this, Arrays.asList(Permission.STORAGE))) {
            // 第一种：用默认的提示语。
            PictureSelectUtils.getByAlbum(MyActivity.this);
        } else {

            AndPermission.with(this)
                    .permission(Permission.STORAGE)
                    .callback(permissionListener)
                    .rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(MyActivity.this, rationale).show();
                        }
                    })
                    .start();
        }
    }

    @OnClick(R.id.setting)
    void setting() {
        ActivityUtils.startActivity(SettingActivity.class);
    }

    @OnClick(R.id.focus)
    void focus() {
        ActivityUtils.startActivity(FocusClubActivity.class);
    }

    @OnClick(R.id.order)
    void order() {
        ActivityUtils.startActivity(OrderActivity.class);
    }

    @OnClick(R.id.send)
    void send() {
        ActivityUtils.startActivity(FTActivity.class);
    }

    private void initData() {

        EasyHttp.get("yuejian6/public/index.php/json/my/index").params("user_id", uid)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String data) {

                        Message msg = Message.obtain(); // 实例化消息对象
                        msg.what = 1; // 消息标识
                        msg.obj = data; // 消息内容存放

                        handler_activity.sendMessage(msg);
                    }

                    @Override
                    public void onError(ApiException error) {
                        Log.d(TAG, "onFailed: " + error);
                    }
                });
    }


    // 步骤1：自定义Handler子类（继承Handler类） & 复写handleMessage（）方法
    class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 0:
                    IsCollection isCollection = null;

                    try {
                        isCollection = JSON.parseObject(msg.obj.toString(), IsCollection.class);
                    } catch (Exception e) {
                        ToastUtils.showShort("获取数据失败");
                        return;
                    }

                    if ("0".equals(isCollection.getError())) {
                        ToastUtils.showShort("修改成功");
                        initData();
                    } else {
                        ToastUtils.showShort("修改失败");
                    }
                    break;
                case 1:
                    MyEntity myEntity = null;

                    try {
                        myEntity = JSON.parseObject(msg.obj.toString(), MyEntity.class);
                    } catch (Exception e) {
                        ToastUtils.showShort("获取数据失败");
                    }


                    Glide.with(context).load(Url.imgUrl + myEntity.getData().getUser_pic()).into(img);
                    name.setText(myEntity.getData().getName());
                    break;
            }
        }
    }

    @OnClick(R.id.logout)
    void logout(){

        SPUtils.getInstance().remove("uid");
        ActivityUtils.finishAllActivities();
        ActivityUtils.startActivity(LoginActivity.class);
        ToastUtils.showLong("登出成功");
    }
}
